﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using KPIS.GERP.GHRMS.APP.Classes;
using Telerik.Web.UI;
using System.Data;
using System.Collections;
using KPIS.GERP.GHRMS.BLL;
using KPIS.GERP.GHRMS.IBLL;
using KPIS.GERP.GHRMS.MODEL;
//using Microsoft.Office.Interop.Excel;
//using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;

namespace KPIS.GERP.GHRMS.APP.App_UI.Forms
{
    public partial class PS_EmployeeSearch : System.Web.UI.Page
    {
        private IJobSiteBLL jobsiteBLL = new JobSiteBLL();
        private IEmployeeTypeBLL etBLL = new EmployeeTypeBLL();
        private IPositionTypeBLL ptBLL = new PositionTypeBLL();
        private IEmployeeBLL empBLL = new EmployeeBLL();
        private IFieldBLL fieldBLL = new FieldBLL();
        private IClassBLL classBLL = new ClassBLL();
        private IMasEducationDegreeBLL dBLL = new MasEducationDegreeBLL();
        private IMasEducationQualificationBLL qualBLL = new MasEducationQualificationBLL();
        private IMasEducationMajorBLL majorBLL = new MasEducationMajorBLL();
        private IMasEducationInstituteBLL insBLL = new MasEducationInstituteBLL();
	    private string pathExcelFolder = @"C:\ExcelExportFolder";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {             
                bindEmpType();
                cmbEmployeeType.SelectedIndex = 0;
                FillDataToJobSite(cmbJobSite, SystemInfo._JobsiteExternal);
                FillDataToJobSite(cmbWorkingJobSite, SystemInfo._JobsiteInternal);
                ConfigureListBoxPositionType();
                ConfigureListBoxClass(1, cblClass1);
                ConfigureListBoxClass(2, cblClass2);
                ConfigureListBoxClass(3, cblClass3);
                ConfigureListBoxClass(4, cblClass4);
                ConfigureListBoxPosition();
                ConfigureListBoxDegree();
                ConfigureListBoxQualification();
                ConfigureListBoxMajor();
                ConfigureListBoxInstitutes();
            }            
        }

        private void ConfigureListBoxPositionType()
        {
            int nEmpType = string.IsNullOrEmpty(cmbEmployeeType.SelectedValue) ? 0 : Int32.Parse(cmbEmployeeType.SelectedValue);
            
            DataSet ds = ptBLL.LoadPositionTypes((int?)null, nEmpType);
            DataTable dt = null;
            if (ds.Tables.Count > 0)
            {
                dt = ds.Tables[0];
                cblPosType.DataSource = dt;
                cblPosType.DataBind();
            }
        }
        private void ConfigureListBoxPosition()
        {
            DataSet ds = fieldBLL.LoadFields("", "", cmbEmployeeType.SelectedValue);
            DataTable dt = null;
            if (ds.Tables.Count > 0)
            {
                dt = ds.Tables[0];
                cmbFieldPosition.DataSource = dt;
                cmbFieldPosition.DataBind();
            }
        }
        private void ConfigureListBoxClass(int PosType, CheckBoxList cmbList)
        {
            DataSet ds = classBLL.LoadClasses((int?)null, PosType, Convert.ToInt32(cmbEmployeeType.SelectedValue));
            DataTable dt = null;
            if (ds.Tables.Count > 0)
            {
                dt = ds.Tables[0];
                cmbList.DataSource = dt;
                cmbList.DataBind();
            }
        }
        private void ConfigureListBoxDegree()
        {
            IList<MasEducationDegreeInfo> infoList = dBLL.ListEducationDegree();
            cmbDegree.DataSource = infoList;
            cmbDegree.DataBind();
        }
        private void ConfigureListBoxQualification()
        {
            DataSet ds = qualBLL.LoadEducationQualifications((int?)null, (int?)null, "");
            DataTable dt = null;
            if (ds.Tables.Count > 0)
            {
                dt = ds.Tables[0];
                cmbQual.DataSource = dt;
                cmbQual.DataBind();
            }
        }
        private void ConfigureListBoxMajor()
        {
            IList<MasEducationMajorInfo> infoList = majorBLL.ListEducationMajors();
            cmbMajor.DataSource = infoList;
            cmbMajor.DataBind();
        }
        private void ConfigureListBoxInstitutes()
        {
            DataSet ds = insBLL.LoadEducationInstitutes((int?)null, true, "");
            DataTable dt = null;
            if (ds.Tables.Count > 0)
            {
                dt = ds.Tables[0];
                cmbInstitutes.DataSource = dt;
                cmbInstitutes.DataBind();
            }
        }
        private void bindEmpType()
        {
            IList<EmployeeTypeInfo> infoList = etBLL.ListEmployeeTypes();
            cmbEmployeeType.DataSource = infoList;
            cmbEmployeeType.DataBind();
        }

        protected void FillDataToJobSite(RadComboBox cmb, string JobSiteType)
        {
            //IList<JobSiteInfo> InfoList = jobsiteBLL.ListJobSiteByTypes(SystemInfo._JobsiteInternal);// .LoadListJobSite(null, Info.External);
            DataSet ds = jobsiteBLL.LoadJobSites("", JobSiteType, "", "");
            DataTable dt = null;
            if (ds.Tables.Count > 0)
            {
                dt = ds.Tables[0];
            }
            cmb.DataSource = dt;
            cmb.DataBind();
        }

        protected void cmdSearch_Click(object sender, EventArgs e)
        {
            DataTable dt = null;

            DataSet ds = empBLL.LoadToExcel(cmbEmployeeType.SelectedValue
                , cmbJobSite.SelectedValue
                , cmbWorkingJobSite.SelectedValue
                , ListCheckedItems(cblPosType)
                , ListCheckedItems(cblClass1)
                , ListCheckedItems(selectFieldPosition)
                , ListCheckedItems(selectDegree)
                , ListCheckedItems(selectQual)
                , ListCheckedItems(selectMajor)
                , ListCheckedItems(selectInstitutes)
                , 0, (DateTime?)null, 0, (DateTime?)null, (int?)null, (int?)null, true);

            if (ds.Tables.Count > 0)
                dt = ds.Tables[0].Copy();

			// ExportDataTableToExcel(dt, @"Result_" + DateTime.Now.ToString("yyyyMMddHHmmss")); problem permission excel CLS class

            Main.ExportExcel(UpdateColumnName(ds));
        } 
        private DataSet UpdateColumnName(DataSet ds)
        {
            for(int i = 0 ; i < ds.Tables[0].Columns.Count ; i++)
            {
                ds.Tables[0].Columns[i].ColumnName = TranslateCustom(ds.Tables[0].Columns[i].ColumnName);
            }
            return ds;
        }
		private string TranslateCustom(string keyEnglish)
		{ 
			var language = new Dictionary<string, string>
				{
					{"NAME", "ชื่อ-นามสกุล"},
					{"FULL_NAME_ENG", "ชื่อ-นามสกุลภาษาอังกฤษ"},
					{"BIRTH_DATE", "วันเกิด"},
					{"POSITION_NO", "เลขตำแหน่ง"},
					{"POSITION_NAME", "ตำแหน่ง"},
					{"CLASS_LEVEL", "ระดับ"},
					{"JOB_SITE_NAME", "สังกัดตามโครงสร้างกฎกระทรวง"},
					{"WORKING_JOB_SITE_NAME", "สังกัดตามโครงสร้างการบริหารจัดการ"},
					{"RETIRE_DATE", "วันเกษียรอายุราชการ"},
					{"CITIZEN", "รหัสประจำตัวประชาชน"},
					{"SALARY", "เงินเดือน"},
					{"DATE_ADMITTED", "วันที่บรรจุ"},
					{"DATE_WORK_START", "วันที่เข้าสู่สังกัดกรม"},
					{"DATE_LATEST_POS", "วันที่ดำรงตำแหน่งสุดท้าย"},
					{"DATE_LATEST_CLASS", "วันที่ดำรงระดับสุดท้าย"},
					{"DATE_LATEST_WORKING_JOB_SITE", "วันที่ทำงานในสังกัดวันสุดท้าย"}
				};

			return language.ContainsKey(keyEnglish) ? language[keyEnglish] : keyEnglish;
		}

        private void ExportDataTableToExcel(DataTable dt, string FileName)
		{

            //Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
            //Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");

            //Excel.Application oXL;
            //Excel.Workbook oWB;
            //Excel.Worksheet oSheet;
            //Excel.Range oRange;

            //oXL = new Excel.Application();

            //oXL.Visible = true;
            //oXL.DisplayAlerts = false;

            //oWB = oXL.Workbooks.Add(Missing.Value);

            //oSheet = (Excel.Worksheet)oWB.ActiveSheet;

            //int rowCount = 1;
            //oSheet.Cells.NumberFormat = "@";

            //foreach (DataRow dr in dt.Rows)
            //{
            //    rowCount += 1;
            //    for (int i = 1; i < dt.Columns.Count + 1; i++)
            //    {
            //        string columnName = dt.Columns[i - 1].ColumnName;
            //        object dataTableCell = dr[i - 1];

            //        if (rowCount == 2)
            //            oSheet.Cells[1, i] = TranslateCustom(columnName);

            //        if (dataTableCell.GetType().Name.StartsWith("Date"))
            //            oSheet.Cells[rowCount, i] = ((DateTime)dataTableCell).ToString("dd/MM/yyyy", new CultureInfo("th-TH"));
            //        else
            //            oSheet.Cells[rowCount, i] = dataTableCell.ToString();
					 
            //    }
            //}

            //oRange = oSheet.get_Range(oSheet.Cells[1, 1],
            //              oSheet.Cells[rowCount, dt.Columns.Count]);
            //oRange.EntireColumn.AutoFit();

            //oSheet = null;
            //oRange = null;

            //if (!System.IO.Directory.Exists(pathExcelFolder))
            //{
            //    System.IO.Directory.CreateDirectory(pathExcelFolder);
            //}

            //oWB.SaveAs(pathExcelFolder + @"\" + FileName + ".xls", Excel.XlFileFormat.xlWorkbookNormal,
            //    Missing.Value, Missing.Value, Missing.Value, Missing.Value,
            //    Excel.XlSaveAsAccessMode.xlExclusive,
            //    Missing.Value, Missing.Value, Missing.Value,
            //    Missing.Value, Missing.Value);
			 
            //oWB.Close(Missing.Value, Missing.Value, Missing.Value);
            //oWB = null;
            //oXL.Quit();  

            //GC.WaitForPendingFinalizers();
            //GC.Collect();
            //GC.WaitForPendingFinalizers();
            //GC.Collect();

            //RedirectToPageDownloadFile(FileName + ".xls");
        }
		protected void RedirectToPageDownloadFile(string fileName)
		{  
			// check to see that the file exists 
			string pathAndName = pathExcelFolder + @"\" + fileName;
			if (File.Exists(pathAndName))
			{

				// for iphones and ipads, this script can cause problems - especially when trying to view videos, so we will redirect to file if on iphone/ipad
				// if (Request.UserAgent.ToLower().Contains("iphone") || Request.UserAgent.ToLower().Contains("ipad")) { Response.Redirect(filePath + '/' + fileName); }
				Response.Clear();
				Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
				Response.WriteFile(pathAndName);
				Response.End();
			}
			else
			{
				throw new Exception("File could not be found");
			} 
		}
        private static void ShowCheckedItems(RadComboBox comboBox, ListBox listBox)
        {
            foreach (RadComboBoxItem item in comboBox.Items)
            {
                ListItem list = new ListItem();

                if (item.Selected)
                {
                    list.Value = comboBox.SelectedValue;
                    list.Text = comboBox.SelectedItem.Text;
                    //item.Value = comboBox.SelectedValue;
                    //item.Text = comboBox.SelectedItem.Text;
                    listBox.Items.Add(list);                   
                }
            }
        }
        private static void MoveCheckedItems(ListBox listBox)
        {
            for (int i = 0; i < listBox.Items.Count ; i++)
            { 
                if (listBox.Items[i].Selected)
                    listBox.Items.Remove(listBox.Items[i]);
            }
                //foreach (ListItem item in listBox.Items)
                //{
                //    //CheckBox chk = (CheckBox)item.FindControl("chk1");
                //    if (item.Selected)
                //        listBox.Items.Remove(item);
                //    //listBox.Items.Clear();
                //}
        }
        private string ListCheckedItems(ListBox listBox)
        {
            ArrayList arr = new ArrayList();

            foreach (ListItem item in listBox.Items)
            {
                arr.Add(item.Value);
            }
            string[] strArray = arr.ToArray(typeof(string)) as string[];
            string str = string.Join(",", strArray);
            return str.Trim();
        }
        private string ListCheckedItems(CheckBoxList checkBoxList)
        {
            ArrayList arr = new ArrayList();

            if (checkBoxList == cblClass1)
            {
                foreach (ListItem item in cblClass1.Items)
                {
                    if (item.Selected)
                        arr.Add(item.Value);
                }
                foreach (ListItem item in cblClass2.Items)
                {
                    if (item.Selected)
                        arr.Add(item.Value);
                }
                foreach (ListItem item in cblClass3.Items)
                {
                    if (item.Selected)
                        arr.Add(item.Value);
                }
                foreach (ListItem item in cblClass4.Items)
                {
                    if (item.Selected)
                        arr.Add(item.Value);
                }
            }
            else
            {
                foreach (ListItem item in checkBoxList.Items)
                {
                    if (item.Selected)
                        arr.Add(item.Value);
                }
            }
            string[] strArray = arr.ToArray(typeof(string)) as string[];
            string str = string.Join(",", strArray);
            return str.Trim();
        }
        protected void btnSelectPosition_Click(object sender, ImageClickEventArgs e)
        {
            ShowCheckedItems(cmbFieldPosition, selectFieldPosition);
        }
        protected void btnMovePosition_Click(object sender, ImageClickEventArgs e)
        {
            MoveCheckedItems(selectFieldPosition);
        }
        protected void btnSelectDegree_Click(object sender, ImageClickEventArgs e)
        {
            ShowCheckedItems(cmbDegree, selectDegree);
        }
        protected void btnSelectQual_Click(object sender, ImageClickEventArgs e)
        {
            ShowCheckedItems(cmbQual, selectQual);
        }

        protected void btnMoveQual_Click(object sender, ImageClickEventArgs e)
        {
            MoveCheckedItems(selectQual);
        }

        protected void btnMoveDegree_Click(object sender, ImageClickEventArgs e)
        {
            MoveCheckedItems(selectDegree);
        }

        protected void btnSelectMajor_Click(object sender, ImageClickEventArgs e)
        {
            ShowCheckedItems(cmbMajor, selectMajor);
        }

        protected void btnMoveMajor_Click(object sender, ImageClickEventArgs e)
        {
            MoveCheckedItems(selectMajor);
        }

        protected void btnSelectIns_Click(object sender, ImageClickEventArgs e)
        {
            ShowCheckedItems(cmbInstitutes, selectInstitutes);
        }

        protected void btnMoveIns_Click(object sender, ImageClickEventArgs e)
        {
            MoveCheckedItems(selectInstitutes);
        }
        
    }
}
